<template>
  <div>
    <van-nav-bar
      title="极客园-登录"
      fixed
      :placeholder="true"
      :safe-area-inset-top="true"
    />
    <van-form @submit="onSubmit">
      <van-field
        v-model="form.mobile"
        required
        name="mobile"
        label="手机号"
        placeholder="手机号"
        :rules="[
          {
            required: true,
            message: '请填写正确的手机号',
            pattern: /^1[3-8]\d{9}$/,
          },
        ]"
      />
      <van-field
        v-model="form.code"
        required
        type="password"
        name="code"
        label="验证码"
        placeholder="验证码"
        :rules="[
          { required: true, message: '请填写验证码', pattern: /^\d{6}$/ },
        ]"
      />
      <div style="margin: 16px">
        <van-button
          round
          block
          type="info"
          native-type="submit"
          :disabled="isLogin"
          :loading="isLogin"
          loading-text="程序员正在为您拼命登录(*╹▽╹*)"
          >登录</van-button
        >
      </div>
    </van-form>
  </div>
</template>

<script>
import { loginAPI } from '@/api'
import { setItem } from '@/utils/token'
import { setStorage } from '@/utils/storage'
export default {
  data () {
    return {
      form: {
        mobile: '18434052295',
        code: '246810'
      },
      isLogin: false
    }
  },
  methods: {
    async onSubmit (values) {
      this.isLogin = true
      try {
        const res = await loginAPI({ ...this.form })
        // console.log(res)
        setItem(res.data.data.token)
        setStorage('refresh_token', res.data.data.refresh_token)
        console.log(res)
        this.$notify({ type: 'success', message: '恭喜您，登陆成功哦！！！' })
        this.isLogin = false
        this.$router.replace({
          // 如果跳转到登录页面时，在路径中携带参数，登录成功后，跳转到该页面
          // 如果不携带参数，就直接跳转到home页面
          path: this.$route.query.pa === undefined ? '/layout' : this.$route.query.pa

        })
      } catch (error) {
        // console.dir(error)
        this.$notify({ type: 'danger', message: error.response.data.message + ',再试试吧' })
        this.isLogin = false
      }
    }
  }
}
</script>
<style>
</style>
